package com.cc.servlet;

import com.alibaba.fastjson2.JSON;
import com.cc.entity.User;
import com.cc.service.UserService;
import com.cc.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@WebServlet("/login")
public class loginServlet extends HttpServlet {
    private UserService  userService = new UserServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        resp.setContentType("application/json;charset=UTF-8");
        Map<String, Object> result = new HashMap<>();
        if (username == null || username.trim().isEmpty() || password == null || password.trim().isEmpty()) {
            result.put("success", false);
            result.put("msg", "用户名或密码不能为空");
            resp.getWriter().write(JSON.toJSONString(result));
            return;
        }
        User user = userService.login(username, password);
        if (user != null) {
            result.put("success", true);
            result.put("user", user);  // 返回用户信息（可选）
            result.put("userId", user.getId());
            req.getSession().setAttribute("user", user);  // 存入Session
        } else {
            result.put("success", false);
            result.put("msg", "用户名或密码错误");
        }

// 统一返回JSON
        resp.getWriter().write(JSON.toJSONString(result));
    }
}
